<?php

namespace App\Http\Controllers;

use App\Models\ThesisDocument;
use App\Models\TopicSelection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ThesisDocumentController extends Controller
{
    public function index()
    {
        $documents = ThesisDocument::with(['topicSelection.student.user', 'topicSelection.thesisTopic.teacher.user'])->get();
        return response()->json($documents);
    }

    public function store(Request $request)
    {
        $request->validate([
            'selection_id' => 'required|exists:topic_selections,id',
            'type' => 'required|in:draft,final',
            'file' => 'required|file|mimes:doc,docx,pdf|max:10240',
            'version' => 'required|string|max:20',
        ]);

        $selection = TopicSelection::findOrFail($request->selection_id);
        if ($selection->status !== 'approved') {
            return response()->json(['message' => 'Topic selection must be approved first'], 422);
        }

        $file = $request->file('file');
        $path = $file->store('thesis_documents');

        $document = ThesisDocument::create([
            'selection_id' => $request->selection_id,
            'type' => $request->type,
            'file_path' => $path,
            'version' => $request->version,
            'submitted_at' => now(),
        ]);

        return response()->json($document->load(['topicSelection.student.user', 'topicSelection.thesisTopic.teacher.user']), 201);
    }

    public function show(ThesisDocument $document)
    {
        return response()->json($document->load(['topicSelection.student.user', 'topicSelection.thesisTopic.teacher.user']));
    }

    public function update(Request $request, ThesisDocument $document)
    {
        $request->validate([
            'feedback' => 'nullable|string',
        ]);

        $document->update($request->only('feedback'));
        return response()->json($document->load(['topicSelection.student.user', 'topicSelection.thesisTopic.teacher.user']));
    }

    public function destroy(ThesisDocument $document)
    {
        Storage::delete($document->file_path);
        $document->delete();
        return response()->json(null, 204);
    }

    public function download(ThesisDocument $document)
    {
        return Storage::download($document->file_path);
    }
} 